var gChoiceCount = 0;

function editQuestionPageSetup() {
	
	var choiceList = document.getElementById("editChoiceList");
	gChoiceCount = (choiceList) ? choiceList.childNodes.length : 0;
	
	var addButton = document.getElementById("addChoiceButton");
	if(addButton) {
	
		addButton.onclick=addChoiceToList;
		if (addButton.captureEvents) 
			addButton.captureEvents(Event.CLICK);
	}
	
	var deleteButtons = getElementsByClass("deleteChoiceButton");
	for(var i=0; i<deleteButtons.length; i++) {
		deleteButtons[i].onclick=removeChoice;
		if(deleteButtons[i].captureEvents)
			deleteButtons[i].captureEvents(Event.CLICK);
	}
}
/* for this to work you need to include global.js BEFORE this file */
registerStartupFunction( editQuestionPageSetup );

function addChoiceToList(evt) {
	var choiceList = document.getElementById("editChoiceList");
	
	var textInput = document.createElement("INPUT");
	textInput.setAttribute("type", "text");
	textInput.setAttribute("name", "choice_" + (++gChoiceCount));
	
	var spacer = document.createTextNode(" ");
	
	var deleteButton = document.createElement("INPUT");
	deleteButton.setAttribute("type", "button");
	deleteButton.setAttribute("class", "deleteChoiceButton");
	deleteButton.setAttribute("value", "delete");
	deleteButton.onclick=removeChoice;
	if(deleteButton.captureEvents)
		deleteButton.captureEvents(Event.CLICK);
	
	var newLi = document.createElement("LI");
	newLi.appendChild(textInput);
	newLi.appendChild(spacer);
	newLi.appendChild(deleteButton);
	
	choiceList.appendChild(newLi);
}

function removeChoice(evt) {
	var target = getEventTarget(evt);
	
	if(target) {
		var listItem = getFirstParentOfType(target, "LI");
		var uList = getFirstParentOfType(listItem, "OL");
		
		if( listItem && uList) {
			uList.removeChild( listItem );
		}
	}
}

function getFirstParentOfType(childElem, type) {
	if(childElem) {
		childElem = childElem.parentNode;
		while(childElem != document) {
			if(childElem.nodeName == type) 
				return childElem;
			childElem = childElem.parentNode;
		}
	}
	return null;
}
